import java.util.ArrayList;
import java.util.List;

public class generateParenthesis {
    public List<String> generateParenthesis(int n) {
        List<String> res = new ArrayList<>();
        a(res,new StringBuilder(),0,0,n);
        return res;
    }
    public void a(List<String> res,StringBuilder sb,int open,int close,int n){
        if(sb.length() == n * 2){
            res.add(sb.toString());
            return;
        }
        if(open < n){
            sb.append('(');
            a(res,sb,open+1,close,n);
            sb.deleteCharAt(sb.length()-1);
        }
        if(close < open){
            sb.append(')');
            a(res,sb,open,close+1,n);
            sb.deleteCharAt(sb.length()-1);
        }
    }
}
